# file:    appleccript.rb
# author:  davidfmiller http://www.fivevoltlogic.com/
# about:   a class that lets you execute applescript through ruby on an os x machine
#
# history: v0.1 monday august 21, 2006
#          - beta release; needs some work but the basics are in place
#
# notes:   appleScript errors will be echoed to the terminal instead of being captured in the result
#     

class AppleScript

	ORANGE_LABEL = 1
	RED_LABEL = 2
	YELLOW_LABEL = 3
	BLUE_LABEL = 4
	PURPLE_LABEL = 5
	GREEN_LABEL = 6
	GRAY_LABEL = 7

	# return an array containing all (known) file extensions that should be treated as bundles
	def AppleScript.bundles
		return ['.vpdoc', '.pkg', '.app', '.pages', '.oo3']
	end

	def AppleScript.labels
		return {ORANGE_LABEL => 'Orange', RED_LABEL => 'Red', YELLOW_LABEL => 'Yellow', BLUE_LABEL => 'Blue', PURPLE_LABEL => 'Purple', GREEN_LABEL => 'Green', GRAY_LABEL => 'Gray'}
	end

	# create a new AppleScript object, specifying either the contents of the script itself
	# (through a String) or a file that contains the contents of the script 
	def initialize(script)
		@cmd = nil;
		if (script.class == String)
			@cmd = script
		elsif (script.class == File)
			@cmd = script
		else
			raise ArgumentError("Argument must either be of type String or File")
		end
	end

	# returns the result (as a string) of executing the AppleScript 
	def run
		path = nil
		if (@cmd.class == String)

			path = File::Separator + 'tmp' + File::Separator + Time.now.to_f.to_s + '.applescript'
			File.open(path, 'w') { |file| file.puts @cmd }
		else
			path = @cmd.path
		end

		return `osascript #{path}`
	end	
end